package com.example.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.software.dto.TaskDTO;
import com.example.software.entity.CompanyInfo;
import com.example.software.entity.Task;
import com.example.software.entity.TaskApplication;
import com.example.software.entity.User;
import com.example.software.mapper.CompanyInfoMapper;
import com.example.software.mapper.TaskApplicationMapper;
import com.example.software.mapper.TaskMapper;
import com.example.software.mapper.UserMapper;
import com.example.software.service.TaskService;
import com.example.software.vo.TaskApplicationVO;
import com.example.software.vo.TaskVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {
    
    private static final Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    
    @Autowired
    private TaskApplicationMapper taskApplicationMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTask(TaskDTO taskDTO, Long userId, String userType) {
        log.debug("创建任务 - 用户ID: {}, 用户类型: {}", userId, userType);
        
        // 检查用户是否是企业用户
        if (!"company".equals(userType)) {
            // 如果从请求中获取的用户类型不是企业，再从数据库查询确认
            User user = userMapper.selectById(userId);
            log.debug("从数据库查询用户 - 用户ID: {}, 用户类型: {}", userId, user != null ? user.getUserType() : null);
            
            if (user == null || !"company".equals(user.getUserType())) {
                log.error("非企业用户尝试创建任务 - 用户ID: {}", userId);
                throw new RuntimeException("只有企业用户才能发布任务");
            }
        }
        
        // 创建任务
        Task task = new Task();
        BeanUtils.copyProperties(taskDTO, task);
        task.setCompanyId(userId);
        task.setStatus("published");
        
        // 确保jobType不为空
        if (task.getJobType() == null || task.getJobType().isEmpty()) {
            task.setJobType("其他");
        }
        
        save(task);
        
        log.debug("任务创建成功 - 任务ID: {}", task.getId());
        return task.getId();
    }
    
    @Override
    public List<TaskVO> getTaskList(Long userId) {
        log.debug("获取任务列表 - 用户ID: {}", userId);
        
        // 获取所有任务，不再仅限于已发布状态
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        // 移除状态过滤条件，返回所有状态的任务
        List<Task> taskList = list(queryWrapper);
        
        if (taskList.isEmpty()) {
            log.debug("任务列表为空");
            return new ArrayList<>();
        }
        
        // 获取企业信息
        List<Long> companyIds = taskList.stream().map(Task::getCompanyId).collect(Collectors.toList());
        LambdaQueryWrapper<CompanyInfo> companyQueryWrapper = new LambdaQueryWrapper<>();
        companyQueryWrapper.in(CompanyInfo::getUserId, companyIds);
        List<CompanyInfo> companyInfoList = companyInfoMapper.selectList(companyQueryWrapper);
        Map<Long, String> companyNameMap = companyInfoList.stream()
                .collect(Collectors.toMap(CompanyInfo::getUserId, CompanyInfo::getCompanyName, (k1, k2) -> k1));
        
        // 获取用户申请的任务 - 只有在userId不为null时才查询
        Map<Long, String> applicationStatusMap = new HashMap<>();
        if (userId != null) {
            LambdaQueryWrapper<TaskApplication> applicationQueryWrapper = new LambdaQueryWrapper<>();
            applicationQueryWrapper.eq(TaskApplication::getWorkerId, userId);
            List<TaskApplication> applicationList = taskApplicationMapper.selectList(applicationQueryWrapper);
            
            // 只有在applicationList不为空时才进行转换
            if (applicationList != null && !applicationList.isEmpty()) {
                applicationStatusMap = applicationList.stream()
                        .collect(Collectors.toMap(TaskApplication::getTaskId, TaskApplication::getStatus, (k1, k2) -> k1));
            }
        } else {
            log.warn("用户ID为空，无法获取任务申请状态");
        }
        
        // 转换为VO
        List<TaskVO> taskVOList = new ArrayList<>();
        for (Task task : taskList) {
            TaskVO taskVO = new TaskVO();
            BeanUtils.copyProperties(task, taskVO);
            taskVO.setCompanyName(companyNameMap.getOrDefault(task.getCompanyId(), "未知企业"));
            taskVO.setIsApplied(applicationStatusMap.containsKey(task.getId()));
            
            // 设置申请状态
            if (applicationStatusMap.containsKey(task.getId())) {
                taskVO.setApplicationStatus(applicationStatusMap.get(task.getId()));
            }
            
            // 检查userId和task.getCompanyId是否都不为null，再进行比较
            if (userId != null && task.getCompanyId() != null) {
                taskVO.setIsOwner(userId.equals(task.getCompanyId()));
            } else {
                taskVO.setIsOwner(false);
            }
            
            taskVOList.add(taskVO);
        }
        
        log.debug("返回任务列表，共 {} 条任务", taskVOList.size());
        return taskVOList;
    }
    
    @Override
    public TaskVO getTaskDetail(Long taskId, Long userId) {
        log.debug("获取任务详情 - 任务ID: {}, 用户ID: {}", taskId, userId);
        
        // 获取任务详情
        Task task = getById(taskId);
        if (task == null) {
            log.error("任务不存在 - 任务ID: {}", taskId);
            throw new RuntimeException("任务不存在");
        }
        
        // 获取企业信息
        CompanyInfo companyInfo = companyInfoMapper.selectOne(
                new LambdaQueryWrapper<CompanyInfo>().eq(CompanyInfo::getUserId, task.getCompanyId())
        );
        
        // 获取用户申请状态
        TaskApplication userApplication = null;
        if (userId != null) {
            userApplication = taskApplicationMapper.selectOne(
                    new LambdaQueryWrapper<TaskApplication>()
                            .eq(TaskApplication::getTaskId, taskId)
                            .eq(TaskApplication::getWorkerId, userId)
            );
        }
        
        // 转换为VO
        TaskVO taskVO = new TaskVO();
        BeanUtils.copyProperties(task, taskVO);
        taskVO.setCompanyName(companyInfo != null ? companyInfo.getCompanyName() : "未知企业");
        taskVO.setIsApplied(userApplication != null);
        taskVO.setIsOwner(userId != null && userId.equals(task.getCompanyId()));
        
        // 设置当前用户的申请状态
        if (userApplication != null) {
            taskVO.setApplicationStatus(userApplication.getStatus());
        }
        
        // 获取已分配的零工名称（当任务状态为已分配或已完成时）
        if ("assigned".equals(task.getStatus()) || "completed".equals(task.getStatus())) {
            // 获取已接受的申请
            TaskApplication acceptedApplication = taskApplicationMapper.selectOne(
                    new LambdaQueryWrapper<TaskApplication>()
                            .eq(TaskApplication::getTaskId, taskId)
                            .eq(TaskApplication::getStatus, "accepted")
            );
            
            if (acceptedApplication != null) {
                // 获取零工用户信息
                User worker = userMapper.selectById(acceptedApplication.getWorkerId());
                if (worker != null) {
                    taskVO.setAssignedWorkerName(worker.getUsername());
                }
            }
        }
        
        // 获取任务的所有申请（仅任务所有者可见）
        if (userId != null && userId.equals(task.getCompanyId())) {
            List<TaskApplication> applications = taskApplicationMapper.selectList(
                    new LambdaQueryWrapper<TaskApplication>()
                            .eq(TaskApplication::getTaskId, taskId)
            );
            
            if (applications != null && !applications.isEmpty()) {
                List<TaskApplicationVO> applicationVOList = applications.stream().map(application -> {
                    TaskApplicationVO applicationVO = new TaskApplicationVO();
                    BeanUtils.copyProperties(application, applicationVO);
                    
                    // 获取零工用户名
                    User worker = userMapper.selectById(application.getWorkerId());
                    if (worker != null) {
                        applicationVO.setWorkerName(worker.getUsername());
                    } else {
                        applicationVO.setWorkerName("未知用户");
                    }
                    
                    return applicationVO;
                }).collect(Collectors.toList());
                
                taskVO.setApplications(applicationVOList);
            }
        }
        
        // 确保jobType不为空
        if (taskVO.getJobType() == null || taskVO.getJobType().isEmpty()) {
            taskVO.setJobType("其他");
        }
        
        log.debug("任务详情获取成功 - 任务ID: {}, 标题: {}, 状态: {}", taskVO.getId(), taskVO.getTitle(), taskVO.getStatus());
        return taskVO;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelTask(Long taskId, Long userId) {
        // 获取任务
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查是否是任务发布者
        if (!userId.equals(task.getCompanyId())) {
            throw new RuntimeException("只有任务发布者才能撤销任务");
        }
        
        // 检查任务状态
        if (!"published".equals(task.getStatus())) {
            throw new RuntimeException("只能撤销已发布的任务");
        }
        
        // 更新任务状态
        task.setStatus("cancelled");
        updateById(task);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applyTask(Long taskId, Long userId) {
        // 获取任务
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查任务状态
        if (!"published".equals(task.getStatus())) {
            throw new RuntimeException("只能申请已发布的任务");
        }
        
        // 检查用户是否是零工用户
        User user = userMapper.selectById(userId);
        if (user == null || !"worker".equals(user.getUserType())) {
            throw new RuntimeException("只有零工用户才能申请任务");
        }
        
        // 检查是否已申请
        TaskApplication existingApplication = taskApplicationMapper.selectOne(
                new LambdaQueryWrapper<TaskApplication>()
                        .eq(TaskApplication::getTaskId, taskId)
                        .eq(TaskApplication::getWorkerId, userId)
        );
        if (existingApplication != null) {
            throw new RuntimeException("您已申请过该任务");
        }
        
        // 创建申请
        TaskApplication application = new TaskApplication();
        application.setTaskId(taskId);
        application.setWorkerId(userId);
        application.setStatus("pending");
        taskApplicationMapper.insert(application);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelApplyTask(Long taskId, Long userId) {
        log.debug("取消申请任务 - 任务ID: {}, 用户ID: {}", taskId, userId);
        
        // 获取申请
        TaskApplication application = taskApplicationMapper.selectOne(
                new LambdaQueryWrapper<TaskApplication>()
                        .eq(TaskApplication::getTaskId, taskId)
                        .eq(TaskApplication::getWorkerId, userId)
        );
        if (application == null) {
            throw new RuntimeException("您未申请过该任务");
        }
        
        // 检查申请状态
        if (!"pending".equals(application.getStatus())) {
            throw new RuntimeException("只能取消待处理的申请");
        }
        
        // 删除申请记录，而不是更新状态
        // 这样用户取消申请后，就像从未申请过一样
        taskApplicationMapper.deleteById(application.getId());
        log.debug("已删除申请记录 - 申请ID: {}", application.getId());
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean acceptApplication(Long applicationId, Long userId) {
        log.debug("接受申请 - 申请ID: {}, 用户ID: {}", applicationId, userId);
        
        // 获取申请
        TaskApplication application = taskApplicationMapper.selectById(applicationId);
        if (application == null) {
            log.error("申请不存在 - 申请ID: {}", applicationId);
            throw new RuntimeException("申请不存在");
        }
        
        // 获取任务
        Task task = getById(application.getTaskId());
        if (task == null) {
            log.error("任务不存在 - 任务ID: {}", application.getTaskId());
            throw new RuntimeException("任务不存在");
        }
        
        // 检查是否是任务发布者
        if (!userId.equals(task.getCompanyId())) {
            log.error("非任务发布者尝试接受申请 - 用户ID: {}, 任务发布者ID: {}", userId, task.getCompanyId());
            throw new RuntimeException("只有任务发布者才能接受申请");
        }
        
        // 检查任务状态
        if (!"published".equals(task.getStatus())) {
            log.error("任务状态不是已发布 - 任务ID: {}, 当前状态: {}", task.getId(), task.getStatus());
            throw new RuntimeException("只能接受已发布任务的申请");
        }
        
        // 检查申请状态
        if (!"pending".equals(application.getStatus())) {
            log.error("申请状态不是待处理 - 申请ID: {}, 当前状态: {}", applicationId, application.getStatus());
            throw new RuntimeException("只能接受待处理的申请");
        }
        
        // 更新申请状态
        application.setStatus("accepted");
        taskApplicationMapper.updateById(application);
        log.debug("更新申请状态为已接受 - 申请ID: {}", applicationId);
        
        // 拒绝该任务的所有其他待处理申请
        LambdaQueryWrapper<TaskApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskApplication::getTaskId, application.getTaskId())
                .eq(TaskApplication::getStatus, "pending")
                .ne(TaskApplication::getId, applicationId);
        
        List<TaskApplication> otherApplications = taskApplicationMapper.selectList(queryWrapper);
        if (!otherApplications.isEmpty()) {
            log.debug("拒绝其他申请 - 任务ID: {}, 申请数量: {}", application.getTaskId(), otherApplications.size());
            for (TaskApplication otherApp : otherApplications) {
                otherApp.setStatus("rejected");
                taskApplicationMapper.updateById(otherApp);
            }
        }
        
        // 更新任务状态
        task.setStatus("assigned");
        updateById(task);
        log.debug("更新任务状态为已分配 - 任务ID: {}", task.getId());
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rejectApplication(Long applicationId, Long userId) {
        // 获取申请
        TaskApplication application = taskApplicationMapper.selectById(applicationId);
        if (application == null) {
            throw new RuntimeException("申请不存在");
        }
        
        // 获取任务
        Task task = getById(application.getTaskId());
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查是否是任务发布者
        if (!userId.equals(task.getCompanyId())) {
            throw new RuntimeException("只有任务发布者才能拒绝申请");
        }
        
        // 检查申请状态
        if (!"pending".equals(application.getStatus())) {
            throw new RuntimeException("只能拒绝待处理的申请");
        }
        
        // 更新申请状态
        application.setStatus("rejected");
        taskApplicationMapper.updateById(application);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeTask(Long taskId, Long userId) {
        // 获取任务
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查是否是任务发布者
        if (!userId.equals(task.getCompanyId())) {
            throw new RuntimeException("只有任务发布者才能完成任务");
        }
        
        // 检查任务状态
        if (!"assigned".equals(task.getStatus())) {
            throw new RuntimeException("只能完成已分配的任务");
        }
        
        // 更新任务状态
        task.setStatus("completed");
        updateById(task);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean terminateTask(Long taskId, Long userId) {
        // 获取任务
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查是否是任务发布者
        if (!userId.equals(task.getCompanyId())) {
            throw new RuntimeException("只有任务发布者才能终止任务");
        }
        
        // 检查任务状态
        if (!"assigned".equals(task.getStatus()) && !"published".equals(task.getStatus())) {
            throw new RuntimeException("只能终止已分配或已发布的任务");
        }
        
        // 更新任务状态
        task.setStatus("cancelled");
        updateById(task);
        
        return true;
    }
    
    @Override
    public Map<String, Object> getTaskStatistics(Long userId) {
        log.debug("获取任务统计数据 - 用户ID: {}", userId);
        
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取用户的任务
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId);
        List<Task> taskList = list(queryWrapper);
        
        // 计算统计数据
        int totalTasks = taskList.size();
        int completedTasks = 0;
        int inProgressTasks = 0;
        BigDecimal totalSalary = BigDecimal.ZERO;
        
        for (Task task : taskList) {
            if ("completed".equals(task.getStatus())) {
                completedTasks++;
                if (task.getSalary() != null) {
                    totalSalary = totalSalary.add(task.getSalary());
                }
            } else if ("assigned".equals(task.getStatus())) {
                inProgressTasks++;
            }
        }
        
        // 设置统计数据
        statistics.put("totalTasks", totalTasks);
        statistics.put("completedTasks", completedTasks);
        statistics.put("inProgressTasks", inProgressTasks);
        statistics.put("averageSalary", completedTasks > 0 ? 
            totalSalary.divide(new BigDecimal(completedTasks), 2, RoundingMode.HALF_UP) : 
            BigDecimal.ZERO);
        
        return statistics;
    }
    
    @Override
    public Map<String, Integer> getTaskStatusDistribution(Long userId) {
        log.debug("获取任务状态分布 - 用户ID: {}", userId);
        
        Map<String, Integer> distribution = new HashMap<>();
        
        // 获取用户的任务列表
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId);
        List<Task> taskList = list(queryWrapper);
        
        // 统计不同状态的任务数量
        int publishedCount = 0;
        int assignedCount = 0;
        int completedCount = 0;
        int cancelledCount = 0;
        
        for (Task task : taskList) {
            switch (task.getStatus()) {
                case "published":
                    publishedCount++;
                    break;
                case "assigned":
                    assignedCount++;
                    break;
                case "completed":
                    completedCount++;
                    break;
                case "cancelled":
                    cancelledCount++;
                    break;
                default:
                    break;
            }
        }
        
        // 设置分布数据
        distribution.put("published", publishedCount);
        distribution.put("assigned", assignedCount);
        distribution.put("completed", completedCount);
        distribution.put("cancelled", cancelledCount);
        
        return distribution;
    }
    
    @Override
    public Map<String, Integer> getTaskTypeDistribution(Long userId) {
        log.debug("获取任务类型分布 - 用户ID: {}", userId);
        
        Map<String, Integer> distribution = new HashMap<>();
        
        // 获取用户的任务列表
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId);
        List<Task> taskList = list(queryWrapper);
        
        // 统计不同类型的任务数量
        for (Task task : taskList) {
            String jobType = task.getJobType();
            if (jobType == null || jobType.isEmpty()) {
                jobType = "其他";
            }
            
            distribution.put(jobType, distribution.getOrDefault(jobType, 0) + 1);
        }
        
        return distribution;
    }
    
    @Override
    public List<Map<String, Object>> getTaskSalaryTrend(Long userId, String period) {
        log.debug("获取任务薪资趋势 - 用户ID: {}, 周期: {}", userId, period);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取用户的任务列表
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId)
                   .eq(Task::getStatus, "completed");
        List<Task> taskList = list(queryWrapper);
        
        // 计算开始日期
        java.time.LocalDate endDate = java.time.LocalDate.now();
        java.time.LocalDate startDate;
        
        switch (period) {
            case "7days":
                startDate = endDate.minusDays(7);
                break;
            case "3months":
                startDate = endDate.minusMonths(3);
                break;
            case "1year":
                startDate = endDate.minusYears(1);
                break;
            case "30days":
            default:
                startDate = endDate.minusDays(30);
                break;
        }
        
        // 按日期分组计算平均薪资
        Map<java.time.LocalDate, List<BigDecimal>> salaryByDate = new HashMap<>();
        
        for (Task task : taskList) {
            if (task.getCreateTime() != null && task.getSalary() != null) {
                java.time.LocalDate taskDate = task.getCreateTime().toLocalDate();
                if (!taskDate.isBefore(startDate) && !taskDate.isAfter(endDate)) {
                    salaryByDate.computeIfAbsent(taskDate, k -> new ArrayList<>())
                              .add(task.getSalary());
                }
            }
        }
        
        // 生成时间序列并计算平均薪资
        java.time.LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", currentDate.toString());
            
            List<BigDecimal> salaries = salaryByDate.get(currentDate);
            if (salaries != null && !salaries.isEmpty()) {
                BigDecimal sum = salaries.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal avgSalary = sum.divide(new BigDecimal(salaries.size()), 2, RoundingMode.HALF_UP);
                item.put("averageSalary", avgSalary);
            } else {
                item.put("averageSalary", BigDecimal.ZERO);
            }
            
            result.add(item);
            currentDate = currentDate.plusDays(1);
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getTaskCompletionStats(Long userId, String range) {
        log.debug("获取任务完成率统计 - 用户ID: {}, 范围: {}", userId, range);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取用户的任务列表
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId);
        List<Task> taskList = list(queryWrapper);
        
        // 计算开始日期
        java.time.LocalDate endDate = java.time.LocalDate.now();
        java.time.LocalDate startDate;
        
        switch (range) {
            case "7days":
                startDate = endDate.minusDays(7);
                break;
            case "30days":
                startDate = endDate.minusDays(30);
                break;
            case "all":
            default:
                startDate = endDate.minusMonths(6); // 默认展示近半年数据
                break;
        }
        
        // 按日期分组统计任务状态
        Map<java.time.LocalDate, Map<String, Integer>> statsByDate = new HashMap<>();
        
        for (Task task : taskList) {
            if (task.getCreateTime() != null) {
                java.time.LocalDate taskDate = task.getCreateTime().toLocalDate();
                if (!taskDate.isBefore(startDate) && !taskDate.isAfter(endDate)) {
                    Map<String, Integer> dateStats = statsByDate.computeIfAbsent(taskDate, 
                        k -> new HashMap<>());
                    
                    // 统计发布数量
                    dateStats.merge("published", 1, Integer::sum);
                    
                    // 统计完成和取消数量
                    if ("completed".equals(task.getStatus())) {
                        dateStats.merge("completed", 1, Integer::sum);
                    } else if ("cancelled".equals(task.getStatus())) {
                        dateStats.merge("cancelled", 1, Integer::sum);
                    }
                }
            }
        }
        
        // 生成时间序列并计算完成率
        java.time.LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", currentDate.toString());
            
            Map<String, Integer> dateStats = statsByDate.get(currentDate);
            if (dateStats != null) {
                int publishedCount = dateStats.getOrDefault("published", 0);
                int completedCount = dateStats.getOrDefault("completed", 0);
                int cancelledCount = dateStats.getOrDefault("cancelled", 0);
                
                item.put("publishedCount", publishedCount);
                item.put("completedCount", completedCount);
                item.put("cancelledCount", cancelledCount);
                
                // 计算完成率
                int completionRate = publishedCount > 0 ? 
                    (completedCount * 100) / publishedCount : 0;
                item.put("completionRate", completionRate);
            } else {
                item.put("publishedCount", 0);
                item.put("completedCount", 0);
                item.put("cancelledCount", 0);
                item.put("completionRate", 0);
            }
            
            result.add(item);
            currentDate = currentDate.plusDays(1);
        }
        
        return result;
    }
    
    @Override
    public Map<String, Integer> getTaskLocationDistribution(Long userId) {
        log.debug("获取任务地区分布 - 用户ID: {}", userId);
        
        // 获取用户的任务列表
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getCompanyId, userId);
        List<Task> taskList = list(queryWrapper);
        
        // 统计不同地区的任务数量
        Map<String, Integer> distribution = new HashMap<>();
        
        for (Task task : taskList) {
            String location = task.getLocation();
            if (location == null || location.isEmpty()) {
                location = "未知地区";
            }
            distribution.put(location, distribution.getOrDefault(location, 0) + 1);
        }
        
        return distribution;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean workerCompleteTask(Long taskId, Long userId) {
        log.debug("零工标记任务为已完成 - 任务ID: {}, 零工ID: {}", taskId, userId);
        
        // 获取任务
        Task task = getById(taskId);
        if (task == null) {
            log.error("任务不存在 - 任务ID: {}", taskId);
            throw new RuntimeException("任务不存在");
        }
        
        // 检查任务状态
        if (!"assigned".equals(task.getStatus())) {
            log.error("只能完成已分配的任务 - 任务ID: {}, 当前状态: {}", taskId, task.getStatus());
            throw new RuntimeException("只能完成已分配的任务");
        }
        
        // 检查是否是该任务被分配的零工
        TaskApplication application = taskApplicationMapper.selectOne(
                new LambdaQueryWrapper<TaskApplication>()
                        .eq(TaskApplication::getTaskId, taskId)
                        .eq(TaskApplication::getWorkerId, userId)
                        .eq(TaskApplication::getStatus, "accepted")
        );
        
        if (application == null) {
            log.error("只有被分配的零工才能标记任务完成 - 任务ID: {}, 零工ID: {}", taskId, userId);
            throw new RuntimeException("您不是该任务的执行者，无法标记完成");
        }
        
        // 更新任务状态为待确认完成
        task.setStatus("pending_completion");
        updateById(task);
        log.debug("零工标记任务完成，等待企业确认 - 任务ID: {}", taskId);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean adminDeleteTask(Long taskId) {
        // 检查任务是否存在
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        log.info("管理员删除任务 - 任务ID: {}, 任务标题: {}", taskId, task.getTitle());
        
        // 删除任务相关的申请记录
        taskApplicationMapper.delete(new LambdaQueryWrapper<TaskApplication>()
                .eq(TaskApplication::getTaskId, taskId));
        
        // 删除任务
        return removeById(taskId);
    }
    
    @Override
    public Map<String, Object> processAnalyticsData(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        
        log.info("处理分析数据文件 - 文件名: {}, 大小: {}", file.getOriginalFilename(), file.getSize());
        
        try {
            // 这里只是一个简单的实现，实际应用中需要根据文件类型和内容进行处理
            // 例如，解析CSV、Excel等格式的文件，处理其中的数据
            
            // 返回处理结果
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("status", "上传成功");
            result.put("message", "数据已处理并更新到系统");
            
            return result;
        } catch (Exception e) {
            log.error("处理分析数据文件失败", e);
            throw new RuntimeException("处理分析数据文件失败: " + e.getMessage());
        }
    }
    
    @Override
    public Map<String, Object> getAdminStatistics() {
        log.info("获取管理员统计数据");
        
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取总用户数量
        Long totalUsersLong = baseMapper.selectCount(null);
        int totalUsers = totalUsersLong != null ? totalUsersLong.intValue() : 0;
        statistics.put("totalUsers", totalUsers);
        
        // 获取企业用户数量
        Long companyUsersLong = baseMapper.selectCount(new LambdaQueryWrapper<Task>()
                .groupBy(Task::getCompanyId)
                .select(Task::getCompanyId));
        int companyUsers = companyUsersLong != null ? companyUsersLong.intValue() : 0;
        statistics.put("companyUsers", companyUsers);
        
        // 获取零工用户数量
        int workerUsers = totalUsers - companyUsers;
        statistics.put("workerUsers", workerUsers);
        
        // 获取总任务数量
        Long totalTasksLong = baseMapper.selectCount(null);
        int totalTasks = totalTasksLong != null ? totalTasksLong.intValue() : 0;
        statistics.put("totalTasks", totalTasks);
        
        // 获取各状态任务数量
        Map<String, Integer> statusCounts = getTaskStatusDistribution(null);
        statistics.put("publishedTasks", statusCounts.getOrDefault("published", 0));
        statistics.put("assignedTasks", statusCounts.getOrDefault("assigned", 0));
        statistics.put("completedTasks", statusCounts.getOrDefault("completed", 0));
        statistics.put("cancelledTasks", statusCounts.getOrDefault("cancelled", 0));
        
        // 获取平均任务报酬
        List<Object> salaries = baseMapper.selectObjs(new LambdaQueryWrapper<Task>()
                .select(Task::getSalary));
        
        double totalSalary = 0;
        int validSalaries = 0;
        
        for (Object obj : salaries) {
            if (obj != null) {
                try {
                    BigDecimal salary = (BigDecimal) obj;
                    totalSalary += salary.doubleValue();
                    validSalaries++;
                } catch (Exception e) {
                    log.error("转换工资数据失败", e);
                }
            }
        }
        
        double averageSalary = validSalaries > 0 ? totalSalary / validSalaries : 0;
        statistics.put("averageSalary", new BigDecimal(averageSalary).setScale(2, RoundingMode.HALF_UP));
        
        return statistics;
    }
} 